import os

from flask import (Blueprint, render_template, request, redirect, url_for, jsonify, session, flash, g)
from werkzeug.utils import secure_filename

from exts import mail, db
from datetime import datetime
from flask_mail import Message
from models import EmailCaptchaModel, UserModel
from forms import RegisterForm, LoginForm, UpdateForm
from werkzeug.security import generate_password_hash, check_password_hash
import config
import string
import random

bp = Blueprint('user', __name__, url_prefix='/user')


# 登录
@bp.route('/login/', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        form = LoginForm(request.form)
        if form.validate():
            email = request.form.get('email')
            password = request.form.get('password')
            user = UserModel.query.filter_by(email=email).first()
            if user and check_password_hash(user.password, password):
                session['user_id'] = user.id
                return redirect('/')
            else:
                flash('邮箱或密码不匹配')
                return redirect(url_for('user.login'))
        else:
            flash('邮箱或密码格式不正确')
            return redirect(url_for('user.login'))
    return render_template('login.html')


# 注册
@bp.route('/register/', methods=['POST', 'GET'])
def register():
    if request.method == 'POST':
        form = RegisterForm(request.form)
        if form.validate():
            email = form.email.data
            username = form.username.data
            password = form.password.data

            # 密码加密
            hash_password = generate_password_hash(password)
            user = UserModel(email=email, username=username, password=hash_password)
            db.session.add(user)
            db.session.commit()
            return redirect(url_for('user.login'))
        else:
            return redirect(url_for('user.register'))
    return render_template('register.html')


# 退出登录
@bp.route('/logout/')
def logout():
    session.clear()
    return redirect(url_for('user.login'))


# 获取验证码
@bp.route('/captcha/', methods=['GET', 'POST'])
def get_captcha():
    email = request.form.get('email')
    letters = string.ascii_letters + string.digits
    captcha = ''.join(random.sample(letters, 4))
    if email:
        message = Message(
            subject='邮箱测试',
            recipients=[email],
            body=f'【芝麻问答】 您的验证码是:{captcha},请不要透露给别人'
        )
        mail.send(message)
        captcha_model = EmailCaptchaModel.query.filter_by(email=email).first()
        if captcha_model:
            captcha_model.captcha = captcha
            captcha_model.create_time = datetime.now()
            db.session.commit()
        else:
            captcha_model = EmailCaptchaModel(email=email, captcha=captcha)
            db.session.add(captcha_model)
            db.session.commit()
        return jsonify({"code": 200})
    else:
        return jsonify({'code': 400, "message": '服务器错误'})


# 进入用户修改界面
@bp.route('/user/', methods=['GET', 'POST'])
def user_user():
    if request.method == 'POST':
        username = request.form.get('username')
        print(username)
        email = request.form.get('email')
        icon = request.files.get('icon')
        icon_name = icon.filename
        suffix = icon_name.rsplit('.')[-1]
        form = UpdateForm(request.form)
        print(form.validate())
        if form.validate():
            if suffix in config.ALLOWED_EXTENSIONS:
                # icon_name = '_'+secure_filename(icon_name)
                file_path = os.path.join(config.UPLOAD_DIR, icon_name)
                print(file_path)
                icon.save(file_path)
                user = g.user
                user.username = username
                user.email = email
                path = f'images/upload/{icon_name}'
                user.icon = path
                db.session.commit()
                return redirect(url_for('user.user_user'))
            # elif suffix not in config.ALLOWED_EXTENSIONS:
            #     flash('图片格式错误')
            #     return redirect(url_for('user.user_user'))
            else:
                user = g.user
                user.username = username
                user.email = email
                db.session.commit()
                return redirect(url_for('user.user_user'))
        else:
            flash('名称必须大于等于3个字符')
            return redirect(url_for('user.user_user'))
    return render_template('user_user.html')
